package com.zh.kmmsample.util

import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation
import io.ktor.client.plugins.logging.DEFAULT
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger
import io.ktor.client.plugins.logging.Logging
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.http.Url
import io.ktor.serialization.kotlinx.json.json
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.IO
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json

/**
 * Http工具类
 */
object HttpUtil {
    /**
     * 超时时间
     */
    private const val mTimeOutSeconds: Long = 15000

    /**
     * Http客户端
     */
//    val mClient: HttpClient = HttpClient(CIO) {
    val mClient: HttpClient = HttpClient() {
        expectSuccess = true

//        engine {
//            maxConnectionsCount = 1000
//            requestTimeout = mTimeOutSeconds
//
//            endpoint {
//                maxConnectionsPerRoute = 100
//                pipelineMaxSize = 20
//                keepAliveTime = mTimeOutSeconds
//                connectTimeout = mTimeOutSeconds
//            }
//        }

        install(Logging) {
            logger = Logger.DEFAULT
            level = LogLevel.HEADERS
        }

        install(ContentNegotiation) {
            json(Json {
                isLenient = true
                //如果Json有字段在实体类中找不到，那么忽略它，没有该配置的话，就会报错
                ignoreUnknownKeys = true
                prettyPrint = true
                isLenient = true
            })
        }
    }

    /**
     * 发起GET请求
     */
    suspend inline fun <reified T> get(
        url: String
    ): T {
        return withContext(Dispatchers.IO) {
            val response = mClient.get(url = Url(url))
            response.call.body()
        }
    }

    /**
     * 发起POST请求
     */
    suspend inline fun <reified T> post(
        url: String
    ): T {
        return withContext(Dispatchers.IO) {
            val response = mClient.post(url = Url(url))
            response.call.body()
        }
    }
}